package cn.zhangxin.newyear.system.verifycode.service.impl;

import cn.zhangxin.newyear.constants.BaseConstants;
import cn.zhangxin.newyear.system.user.domain.User;
import cn.zhangxin.newyear.system.user.mapper.UserMapper;
import cn.zhangxin.newyear.system.verifycode.domain.EmailCode;
import cn.zhangxin.newyear.system.verifycode.service.IVerifycodeService;
import cn.zhangxin.newyear.utils.BusinessException;
import cn.zhangxin.newyear.utils.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.index.PathBasedRedisIndexDefinition;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.TimeUnit;

@Service
public class VerifycodeServiceImpl implements IVerifycodeService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${sentEmail}")
    private String sentEmail;

    @Override
    public void sentEmailCode(EmailCode emailCode) {

        //邮箱校验
        if (emailCode.getEmail()==null){
            throw new BusinessException("邮箱不能为空");
        }
        //查看该邮箱是否已经被注册
        User oneByEmailUser = userMapper.findOneByEmailUser(emailCode.getEmail());
        if (oneByEmailUser!=null){
            throw new BusinessException("该邮箱已经被注册");
        }
        //图片验证码校验
        if (emailCode.getImageCode()==null){
            throw new BusinessException("图片验证码不能为空");
        }
        //判断前端穿回来的图片验证码是否与redis数据库中的验证码相同
        String imageCodeKey = emailCode.getImageCodeKey();
        String code = (String)redisTemplate.opsForValue().get(imageCodeKey);
        if (!code.equals(emailCode.getImageCode())){
            throw new BusinessException("图片验证码错误");
        }
        //发送邮件验证码验证码
        //生成6位数验证码
        String s = (String)redisTemplate.opsForValue().get(emailCode.getEmail() + BaseConstants.Redis.REGISTER);
        Long saveTime = (Long)redisTemplate.opsForValue().get(emailCode.getEmail() + BaseConstants.Redis.REGISTERTime);
        //如果取出来为空，就发送一个生成一个6位数验证码
        if (s==null){
            //获得6位数验证码
            String randomString = StrUtils.getRandomString(6);
            //将密码存入redis 并设置3分钟
            redisTemplate.opsForValue().set(emailCode.getEmail() + BaseConstants.Redis.REGISTER,randomString,3, TimeUnit.MINUTES);
            //将发送验证码的时间搓也存入redis，并设置3分钟
            redisTemplate.opsForValue().set(emailCode.getEmail() + BaseConstants.Redis.REGISTERTime,System.currentTimeMillis(),3,TimeUnit.MINUTES);
            //发送邮箱验证码
            System.out.println(randomString);
            //发送邮件
            toEmail("邮箱注册验证码",randomString,emailCode.getEmail());
        }else {
            //获得当前时间戳
            long systemTime = System.currentTimeMillis();
            if (systemTime-saveTime<60000){
                throw new BusinessException("非法访问");
            }else {
                //发送从邮箱中取出来的验证码
                System.out.println(s);
                //发送验证码
                toEmail("邮箱注册验证码",s,emailCode.getEmail());
            }
        }

    }
    //邮件发送方法
    private void toEmail(String titleMsg,String emailCode,String toEmail){
        try {
            //创建复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //发送复杂邮件的工具类
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom(sentEmail);//发送的账号
            helper.setSubject(titleMsg);
            //拼接验证码信息
            helper.setText("<h1>"+emailCode+"</h1>",true);
            //收件人
            helper.setTo(toEmail);
            //发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
